#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QStringList>

#include <QDebug>

#include <QMessageBox>

#include <QDateTime>

#include <QFileDialog>

#include <cstring>

#include <QStringList>

#define UART_TX_LEN 64

int pb_open_com_flag;  //串口标志位

char send_buf[UART_TX_LEN];

char *clear_uart_string(void){

    memset(&send_buf,0,UART_TX_LEN);    //清空缓冲区

    return send_buf;

}

//构造函数
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->connect(ui->pb_open_com,SIGNAL(clicked()),this,SLOT(on_pb_send_com_clicked()));//串口打开

    this->connect(ui->pb_file_position,SIGNAL(clicked()),this,SLOT(current_data_time()));  //保存文件

    this->connect(ui->pb_file_position,SIGNAL(clicked()),this,SLOT(on_pb_file_position_slot()));  //获取文件名
}

//发送数据
void MainWindow::send_uart_string(char *p_tx){

    if(mycom->isOpen()){

        ui->textEdit_tx->append(p_tx);

        mycom->write(p_tx);

    }else{

        QMessageBox::warning(this,tr("Waring"),tr("请先打开串口"));

        return;

    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

//设置使能

void MainWindow::on_pb_open_com_clicked()

{

    if(pb_open_com_flag == 1){

        mycom->close();

        ui->pb_open_com->setText("打开串口");

        ui->label_com_info->setText("Close");

        ui->cb_baud_rate->setEnabled(true);

        ui->cb_data_bit->setEnabled(true);

        ui->cb_parity_bit->setEnabled(true);

        ui->cb_stop_bit->setEnabled(true);

        ui->cb_serial_num->setEnabled(true);

        ui->cb_control->setEnabled(true);

        pb_open_com_flag = 0;  //标志位表示串口已关闭

    }else{

        mycom = new QSerialPort();  //创建串口

        mycom->setPortName(ui->cb_serial_num->currentText());

        mycom->open(QIODevice::ReadWrite);

        mycom->setBaudRate(ui->cb_baud_rate->currentText().toInt()); //设置波特率

        if(ui->cb_data_bit->currentText() == tr("7位"))   //设置数据位

            mycom->setDataBits(QSerialPort::Data7);

        else

            mycom->setDataBits(QSerialPort::Data8);

        if(ui->cb_parity_bit->currentText() == tr("无")) //奇偶校验

            mycom->setParity(QSerialPort::NoParity);

        else if(ui->cb_parity_bit->currentText() == tr("奇校验"))

            mycom->setParity(QSerialPort::OddParity);

        else if(ui->cb_parity_bit->currentText() == tr("偶校验"))

            mycom->setParity(QSerialPort::EvenParity);

        else if(ui->cb_parity_bit->currentText() == tr("空格"))

            mycom->setParity(QSerialPort::SpaceParity);

        else

            mycom->setParity(QSerialPort::MarkParity);

        if(ui->cb_stop_bit->currentText() == tr("1位"))  //停止位

            mycom->setStopBits(QSerialPort::OneStop);

        else

            mycom->setStopBits(QSerialPort::TwoStop);

        if(ui->cb_control->currentText() == tr("Xon/Xoff"))  //流控制

            mycom->setFlowControl(QSerialPort::SoftwareControl);

        else if(ui->cb_control->currentText() == tr("硬件"))

            mycom->setFlowControl(QSerialPort::HardwareControl);

        else

            mycom->setFlowControl(QSerialPort::NoFlowControl);

        if(mycom->isOpen()){

            ui->pb_open_com->setText("关闭串口");

            ui->label_com_info->setText("Open");

            ui->cb_baud_rate->setEnabled(false);

            ui->cb_data_bit->setEnabled(false);

            ui->cb_parity_bit->setEnabled(false);

            ui->cb_stop_bit->setEnabled(false);

            ui->cb_serial_num->setEnabled(false);

            ui->cb_control->setEnabled(false);

            mythread = new MyThread(mycom);

            this->connect(mythread,SIGNAL(comRecive()),this,SLOT(displayRxData()));

            mythread->start();

            pb_open_com_flag = 1;  //标志位表示串口已打开

        }else{

            QMessageBox::warning(this,tr("警告"),tr("串口未打开或被占用"));

            pb_open_com_flag = 0;

            return ;

        }

    }

}

//接受显示数据

void MainWindow::displayRxData(){

    RequestData.clear();

    RequestData = mycom->readAll();

    ui->textEdit_rx->append(RequestData.data());

    RequestData.clear();

}

//保存文件

void MainWindow::on_pb_file_position_slot(){

    if(!ui->textEdit_rx->toPlainText().isEmpty()){

        QString path = "C:/temp/";

        QDateTime current = QDateTime::currentDateTime();

        path = current.toString("yyyyMMddhhmmss");

        path += ".txt";

        QString filepath=\

                QFileDialog::getSaveFileName(this,"Save File",path,\

                                             tr("All (*.*);;Text (*.txt);;C文件 (*.c *.cpp);;PDF (*.pdf);;Word, *.doc)"));

        QFile *file = new QFile;

        file->setFileName(filepath);

        bool ok = file->open(QIODevice::WriteOnly);

        if(ok){

            QTextStream out(file);

            out << ui->textEdit_rx->toPlainText();

            QDir dir;

            ui->label_file_position->setText(QString(dir.filePath(filepath)));

            file->close();

            delete file;

        }

        else{

            QMessageBox::warning(this,tr("警告"),tr("未能保存成功，请重新保存"));

            return ;

        }

    }else{

        QMessageBox::warning(this,tr("警告"),tr("接收数据为空"));

    }

}

//清空发送数据

void MainWindow::on_pb_clear_send_data_clicked()

{

    ui->textEdit_tx->clear();

}

//清空接收数据

void MainWindow::on_pb_clear_request_data_clicked()

{

    ui->textEdit_rx->clear();

}

void MainWindow::on_pushButton_clicked()

{

    char *p_tx = clear_uart_string();

    QString  str = ui->lineEdit->text();

    QByteArray ba = str.toLatin1();

    p_tx = ba.data();

    send_uart_string(p_tx);

}
